package com.gowhere.filters;

import com.gowhere.domain.UserInfo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();

        //静态资源和登录相关功能放行
        if (uri.contains("/img") || uri.contains("/plugins") || uri.contains("/css")  || uri.contains("/validate") || uri.endsWith("login")|| uri.endsWith("check") || uri.endsWith("login.jsp")) {
            filterChain.doFilter(req, resp);
        } else {
            //存在登录信息自动放行
            UserInfo user = (UserInfo) req.getSession().getAttribute("user");
            if (user != null) {
                filterChain.doFilter(req, resp);
            } else {
                int count=0;
                UserInfo u = new UserInfo();
                Cookie[] cookies = req.getCookies();
                for (Cookie cookie : cookies) {
                    if ("uname".equals(cookie.getName())) {
                        u.setUsername(cookie.getValue());

                        count++;
                    } else if ("pword".equals(cookie.getName())) {
                        u.setPassword(cookie.getValue());
                        count++;
                    }
                }
                if (count==2){
                    req.getSession().setAttribute("user",u);
                    resp.sendRedirect(req.getContextPath() + "/index.jsp");

                }else {
                    //不存在登录信息重定向到登录页面
                    resp.sendRedirect(req.getContextPath() + "/pages/login.jsp");
                }

            }
        }
    }

    @Override
    public void destroy() {

    }
}
